package com.testdemo.common.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.design.widget.TabLayout;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.ScrollView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.AbstractDraweeController;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.postprocessors.IterativeBoxBlurPostProcessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.testdemo.MyApplication;
import com.testdemo.R;
import com.testdemo.common.base.BaseActivity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Response;

/**
 * Created by dell on 2017/11/28.
 * <p>
 * //////////       目录：
 * //////////
 * //////////       *******************************     尺寸相关        ********************************************
 * //////////
 * //////////       dp转px   {@link #dip2px(float dpValue)}
 * //////////
 * //////////       获取屏幕宽度  {@link #getDisplayWidth(Activity a)}
 * //////////
 * //////////       *******************************     时间和数字格式相关       ********************************************
 * //////////
 * //////////       （long 毫秒数）时间戳转化为时间格式    {@link #toTimeString(long millis, String format)}
 * //////////
 * //////////       （String 毫秒数）时间戳转化为时间格式  {@link #toTimeString(String millis, String format)}
 * //////////
 * //////////       将秒数转为时间格式   {@link #secondsToTimeString(int seconds)}
 * //////////
 * //////////       数字格式化   {@link #numFormat(String numString, String formatString, RoundingMode mode)}
 * //////////
 * //////////       *******************************     输入框相关        ********************************************
 * //////////
 * //////////       限制输入两位小数    {@link #setInput(EditText et, CharSequence s, int pointsNum)}
 * //////////
 * //////////       判断email格式是否正确   {@link #isEmail(String email)}
 * //////////
 * //////////       键盘弹出收起时布局自动滚动   {@link #controlKeyboardLayout(ScrollView scrollView, int dpHeight)}
 * //////////
 * //////////       *******************************     文本设置相关      ********************************************
 * //////////
 * //////////       去掉字符串的空指针显示     {@link #noNullString(String string)}
 * //////////
 * //////////       禁止EditText输入特殊字符    {@link #setEditTextInhibitInputSpeChat(EditText editText)}
 * //////////
 * //////////       复制文本    {@link #copyText(String content)}
 * //////////
 * //////////       设置文本中指定字符串的颜色和字号    {@link #setSpannableText(String allStr, String targetStr, int colorId, int textSpSize)}
 * //////////
 * //////////       设置文本中指定位置的颜色和字号     {@link #setSpannableText(String allStr, int start, int end, int colorId, int textSpSize)}
 * //////////
 * //////////       获取颜色    {@link #getColor(int colorId)}
 * //////////
 * //////////       获取字符串   {@link #getString(int strId)}
 * //////////
 * //////////       Html.formHtml 版本适配方法    {@link #fromHtml(String html)}
 * //////////
 * //////////       获得html格式的字符串    {@link #getHtmlString(Context context, int color, String content)}
 * //////////
 * //////////       获得多种文字颜色混合字符串的html  {@link #getHtmlText(List colors, List contents)}
 * //////////
 * //////////       *******************************     版本及设备信息相关       ********************************************
 * //////////
 * //////////       获取应用的版本号    {@link #getLocalVersionCode()}
 * //////////
 * //////////       获取应用的版本名称   {@link #getLocalVersionName()}
 * //////////
 * //////////       获取android设备id   {@link #getDeviceId()}
 * //////////
 * //////////       *******************************     其他      ********************************************
 * //////////
 * //////////       设置TabLayout下划线的边距dp数    {@link #setTabLayoutLineMargin(int dp, TabLayout tl)}
 * //////////
 * //////////       两个经纬点之间的距离  {@link #getDistance(double lat1, double lon1, double lat2, double lon2)}
 * //////////
 * //////////       list去除重复数据  {@link #clearRepeat(List array)}
 * //////////
 * //////////       通过android的Uri获取真实路径     {@link #getPathByUri(Uri uri)}
 * <p>
 * //////////       高斯模糊 {@link #gaussianBlur(SimpleDraweeView, Uri)}
 * <p>
 * //////////      fresco按尺寸压缩 {@link #setFrescoCompress(SimpleDraweeView simpleDraweeView, Uri uri, int width, int height)}
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 * //////////
 */
public class CommonUtil {

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(float dpValue) {
        final float scale = MyApplication.myApplication.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 时间戳转化为时间格式，
     * 格式字段传空则使用yyyy-mm-dd HH:mm:ss格式
     *
     * @param millis 时间戳
     * @param format 时间格式
     * @return
     */
    public static String toTimeString(long millis, String format) {
        String time = "";
        if (TextUtils.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date dt = new Date(millis);
            time = sdf.format(dt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 时间戳转化为时间格式，
     * 格式字段传空则使用yyyy-mm-dd HH:mm:ss格式
     *
     * @param millis 时间戳(字符)
     * @param format 时间格式
     * @return
     */
    public static String toTimeString(String millis, String format) {
        String time = "";
        try {
            long l = Long.parseLong(millis);
            time = toTimeString(l, format);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }


    /**
     * 将秒数转为时间格式
     * ( 3671 >> 01:01:11)
     *
     * @param seconds
     * @return
     */
    public static String secondsToTimeString(int seconds) {
        String ss = seconds % 60 + "";
        if (ss.length() == 1) {
            ss = "0" + ss;
        }
        String mm = "00";
        try {
            mm = seconds / 60 % 60 + "";
            if (mm.length() == 1) {
                mm = "0" + mm;
            }
        } catch (Exception e) {
        }

        String hh = "";
        try {
            if (seconds / (60 * 60) > 0) {
                hh = seconds / (60 * 60) + "";
                if (hh.length() == 1) {
                    hh = "0" + hh;
                }
                hh += ":";
            }
        } catch (Exception e) {
        }

        return hh + mm + ":" + ss;
    }


    /**
     * @param et
     * @param s
     * @param pointsNum 小数点位数
     */
    public static void setInput(EditText et, CharSequence s, int pointsNum) {
        try {
            if (s.toString().contains(".")) {
                if (s.length() - 1 - s.toString().indexOf(".") > pointsNum) {
                    s = s.toString().subSequence(0, s.toString().indexOf(".") + pointsNum + 1);
                    et.setText(s);
                    et.setSelection(s.length());
                }
            }
            if (s.toString().trim().substring(0).equals(".")) {
                s = "0" + s;
                et.setText(s);
                et.setSelection(2);
            }
            if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                if (!s.toString().substring(1, 2).equals(".")) {
                    String str = s.toString().replaceAll("0", "");
                    if (TextUtils.isEmpty(str)) {
                        str = str + "0";
                        et.setText(str);
                    } else {
                        et.setText(str);
                    }
                    et.setSelection(str.length());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断email格式是否正确
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {

        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

        Pattern p = Pattern.compile(str);

        Matcher m = p.matcher(email);

        return m.matches();

    }

    /**
     * 获取应用的版本号
     *
     * @return
     */
    public static int getLocalVersionCode() {
        int localVersion = 0;
        Context context = MyApplication.myApplication;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    /**
     * 获取应用的版本名称
     *
     * @return
     */
    public static String getLocalVersionName() {
        String localVersionName = "1.0.0";
        Context context = MyApplication.myApplication;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            localVersionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersionName;
    }

    /**
     * 键盘弹出收起时布局自动滚动
     *
     * @param scrollView 被键盘遮挡的scrollToView，滚动root,使scrollToView在root可视区域的底部
     */
    public static void controlKeyboardLayout(final ScrollView scrollView, final int dpHeight) {

        scrollView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if ((oldBottom - bottom) > 100) {
                    scrollView.smoothScrollTo(0, dip2px(dpHeight));
                } else if ((bottom - oldBottom) > 100) {
                    scrollView.smoothScrollTo(0, 0);
                }
            }
        });
    }

    /**
     * 设置文本中指定字符串的颜色和字号
     *
     * @param allStr     全部字符串
     * @param targetStr  需要匹配的字符串
     * @param colorId    匹配的字符串的文字颜色
     * @param textSpSize 匹配的字符串的文字大小
     */
    @TargetApi(Build.VERSION_CODES.M)
    public static SpannableString setSpannableText(String allStr, String targetStr, int colorId, int textSpSize) {
        SpannableString spannable = new SpannableString(allStr);
        String string = spannable.toString();

        int start = string.indexOf(targetStr);
        if (start == -1) {
            return spannable;
        }
        int end = start + targetStr.length();

        if (colorId != 0) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(getColor(colorId));
            spannable.setSpan(fcs, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (textSpSize != 0) {
            AbsoluteSizeSpan ass = new AbsoluteSizeSpan(CommonUtil.dip2px(textSpSize));
            spannable.setSpan(ass, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannable;
    }

    /**
     * 设置文本中指定位置的颜色和字号
     *
     * @param allStr     全部字符串
     * @param start      需要匹配的字符串开始角标
     * @param end        需要匹配的字符串结束角标
     * @param colorId    匹配的字符串的文字颜色
     * @param textSpSize 匹配的字符串的文字大小
     */
    @TargetApi(Build.VERSION_CODES.M)
    public static void setSpannableText(String allStr, int start, int end, int colorId, int textSpSize) {
        SpannableString spannable = new SpannableString(allStr);
        if (colorId != 0) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(getColor(colorId));
            spannable.setSpan(fcs, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (textSpSize != 0) {
            AbsoluteSizeSpan ass = new AbsoluteSizeSpan(CommonUtil.dip2px(textSpSize));
            spannable.setSpan(ass, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    /**
     * 获取颜色
     *
     * @param colorId
     * @return
     */
    public static int getColor(@ColorRes int colorId) {
        if (Build.VERSION.SDK_INT >= 23)
            return MyApplication.myApplication.getResources().getColor(colorId, null);
        else
            return MyApplication.myApplication.getResources().getColor(colorId);
    }


    /**
     * 获取字符串
     *
     * @param strId
     * @return
     */
    public static String getString(@StringRes int strId) {
        try {
            return MyApplication.myApplication.mActivities.get(0).getString(strId);
        } catch (Exception e) {
            return MyApplication.myApplication.getResources().getString(strId);
        }
    }


    /**
     * 获取android设备id
     *
     * @describe 获取android设备id @method getDeviceId @return @return
     * String @throws
     */
    public static String getDeviceId() {
        try {
            TelephonyManager tm = (TelephonyManager) MyApplication.myApplication.getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getDeviceId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * Html.formHtml 版本适配方法
     *
     * @param html
     */

    public static Spanned fromHtml(String html) {
        Spanned result;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
        } else {
            result = Html.fromHtml(html);
        }
        return result;
    }

    /**
     * 获得html格式的字符串
     *
     * @param context
     * @param color   文字颜色
     * @param content 文字内容
     * @return
     */
    public static String getHtmlString(Context context, int color, String content) {
        return "<font color= '" + context.getResources().getColor(color) + "'>" + content + "</font>";
    }

    /**
     * 获得html格式的字符串
     *
     * @param color   文字颜色
     * @param content 文字内容
     * @return
     */
    public static String getHtmlString(@ColorRes int color, String content) {
        return "<font color= '" + getColor(color) + "'>" + content + "</font>";
    }


    /**
     * 获得多种文字颜色混合字符串的html
     *
     * @param colors
     * @param contents
     * @return
     */
    public static CharSequence getHtmlText(List<Integer> colors, List<String> contents) {
        if (colors == null || contents == null || colors.size() != contents.size()) {
            return null;
        }

        MyApplication app = MyApplication.myApplication;

        String htmlStr = null;
        for (int i = 0; i < colors.size(); i++) {
            if (i == 0) {
                htmlStr = getHtmlString(app, colors.get(i), contents.get(i));
            } else {
                htmlStr += getHtmlString(app, colors.get(i), contents.get(i));
            }
        }

        return htmlStr == null ? null : Html.fromHtml(htmlStr);
    }


    /**
     * 设置TabLayout下划线的边距dp数
     * 设置TabLayout下划线的边距dp数，该方法要放在TabLayout绘制出来以后
     *
     * @param dp
     * @param tl
     */
    public static void setTabLayoutLineMargin(int dp, TabLayout tl) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
            return;
        try {
            Class tabLayout = tl.getClass();
            Field tabStrip = tabLayout.getDeclaredField("mTabStrip");
            tabStrip.setAccessible(true);
            LinearLayout ll_tab = (LinearLayout) tabStrip.get(tl);
            for (int i = 0; i < ll_tab.getChildCount(); i++) {
                View child = ll_tab.getChildAt(i);
                child.setPadding(0, 0, 0, 0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                params.setMarginStart(CommonUtil.dip2px(dp));
                params.setMarginEnd(CommonUtil.dip2px(dp));
                child.setLayoutParams(params);
                child.invalidate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 去掉字符串的空指针显示
     *
     * @param string
     * @return
     */
    public static String noNullString(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        return string;
    }


    /**
     * 两个经纬点之间的距离
     *
     * @param lat1
     * @param lon1
     * @param lat2
     * @param lon2
     * @return
     */
    public static double getDistance(double lat1, double lon1, double lat2, double lon2) {
        float[] results = new float[1];
        Location.distanceBetween(lat1, lon1, lat2, lon2, results);
        return results[0];
    }


    /**
     * list去除重复数据
     *
     * @param array
     * @return
     */
    public static List clearRepeat(List array) {
        List arr = new ArrayList();
        Iterator it = array.iterator();
        while (it.hasNext()) {
            Object obj = it.next();
            if (!arr.contains(obj))
                arr.add(obj);
        }
        return arr;
    }


    /**
     * 获取屏幕宽度
     *
     * @param a
     * @return
     */
    public static int getDisplayWidth(Activity a) {
        WindowManager wm = a.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }

    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText
     */
    public static void setEditTextInhibitInputSpeChat(final EditText editText) {

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                //\u4e00-\u9fa5 汉字
                //\u0401-\u04e9 俄文
                String speChat = "^[\\u4e00-\\u9fa5a-zA-Z0-9\\u0401-\\u04e9]+$";//
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (!matcher.find()) return "";
                else return null;
            }
        };

        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(30), filter});
    }


    /**
     * 复制文本
     *
     * @param content 文本
     */
    public static void copyText(String content) {
        ClipboardManager clip = (ClipboardManager) MyApplication.myApplication.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", content);
        // 将ClipData内容放到系统剪贴板里。
        clip.setPrimaryClip(mClipData);
    }


    /**
     * 数字格式化
     *
     * @param numString
     * @param formatString
     * @param mode
     * @return numFormat("98.874555",   "0.##", RoundingMode.HALF_UP)    return 98.87
     */
    public static String numFormat(String numString, String formatString, RoundingMode mode) {
        try {
            DecimalFormat df = new DecimalFormat(formatString);
            df.setRoundingMode(mode);
            try {
                return df.format(Double.parseDouble(numString));
            } catch (Exception e) {
            }
            return df.format(Double.parseDouble(numString));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0";
    }

    /**
     * 数字格式化
     *
     * @param numDouble
     * @param formatString
     * @param mode
     * @return numFormat("98.874555",   "0.##", RoundingMode.HALF_UP)    return 98.87
     */
    public static String numFormat(double numDouble, String formatString, RoundingMode mode) {
        try {
            DecimalFormat df = new DecimalFormat(formatString);
            df.setRoundingMode(mode);
            try {
                return df.format(numDouble);
            } catch (Exception e) {
            }
            return df.format(numDouble);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0";
    }

    /**
     * 获取交易价格
     *
     * @param money
     * @return
     */
    public static String getTradeMoney(String money) {
        try {
            if (!TextUtils.isEmpty(money)) {
                return numFormat(Str2Double(money), "0.000", RoundingMode.DOWN);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0.000";
    }

    /**
     * 字符串转double
     *
     * @param value
     * @return
     */
    public static double Str2Double(@NonNull String value) {
        try {
            if (!TextUtils.isEmpty(value)) {
                return Double.valueOf(value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 通过android的Uri获取真实路径
     *
     * @param uri
     * @return
     */
    public static String getPathByUri(final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = MyApplication.myApplication.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    public static void setRadioButtonLeftDrawable(RadioButton radioButton, Drawable drawable, int drawableSiZeDp) {
        //定义底部标签图片大小
        int size = dip2px(drawableSiZeDp);
        drawable.setBounds(0, 0, size, size);//距左右边距离，距上下边距离，长度,宽度
        radioButton.setCompoundDrawables(drawable, null, null, null);//只放左边面
    }


    /**
     * 获取状态栏的高度
     *
     * @return
     */
    public static int getStatusBarHeight() {
        int resourceId = MyApplication.myApplication.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            return MyApplication.myApplication.getResources().getDimensionPixelSize(resourceId);
        } else {
            return 0;
        }
    }

    /**
     * 把某个占位view的高度设置成状态栏的高度
     *
     * @param viewStatus
     */
    public static void setViewAsStatusBarHeight(View viewStatus) {
        if (Build.VERSION.SDK_INT >= 19) {
            ViewGroup.LayoutParams lp = viewStatus.getLayoutParams();
            lp.height = getStatusBarHeight();
            viewStatus.setLayoutParams(lp);
        } else {
            viewStatus.setVisibility(View.GONE);
        }
    }


    /**
     * 加法
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }

    /**
     * 减法
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 乘法
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }


    /**
     * 除法
     *
     * @param v1
     * @param v2
     * @param scale 精确范围 精确度不能小于0
     * @return
     */
    public static double divide(double v1, double v2, int scale) {
        if (scale > 0) {
            //如果精确范围小于0，抛出异常信息
            BigDecimal b1 = new BigDecimal(Double.toString(v1));
            BigDecimal b2 = new BigDecimal(Double.toString(v2));
            return b1.divide(b2, scale, BigDecimal.ROUND_DOWN).doubleValue();
        }
        return 0;
    }

    /**
     * 防止图片oom
     *
     * @return
     */
    public static Bitmap getBitmapForImgResources(Context mContext, int imgId) {
        Bitmap bitmap = null;
        InputStream is = null;
        try {
            is = mContext.getResources().openRawResource(imgId);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            options.inPurgeable = true;
            options.inInputShareable = true;
            options.inSampleSize = 1;
            bitmap = BitmapFactory.decodeStream(is, null, options);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }


    /**
     * 是否联网
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        try {
            ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = conn.getActiveNetworkInfo();
            return (info != null && info.isConnected());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 字符串强转成数字
     *
     * @param data
     * @return
     */
    public static int str2Int(@NonNull String data) {
        int num = 0;
        if (!TextUtils.isEmpty(data)) {
            try {
                num = Integer.valueOf(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return num;
    }

    /**
     * 高斯模糊效果
     */
    public static void gaussianBlur(SimpleDraweeView sdv, Uri uri) {
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .setPostprocessor(new IterativeBoxBlurPostProcessor(2, 30))
                .build();
        AbstractDraweeController controller = Fresco.newDraweeControllerBuilder()
                .setOldController(sdv.getController())
                .setImageRequest(request)
                .build();
        sdv.setController(controller);
    }

    /**
     * 验证密码是否符合格式（必须包含大写字母和小写字母）
     *
     * @param password
     * @return
     */
    public static boolean passwordFormatOk(String password) {
        Pattern p1 = Pattern.compile("[a-z]+");
        Pattern p2 = Pattern.compile("[A-Z]+");
        return p1.matcher(password).find() && p2.matcher(password).find();
    }


    /**
     * Fresco 按尺寸压缩 图片（防止空白图）
     *
     * @param simpleDraweeView
     * @param uri
     * @param width
     * @param height
     */
    public static void setFrescoCompress(SimpleDraweeView simpleDraweeView, Uri uri, int width, int height) {
        if (uri == null) {
            return;
        }
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .setResizeOptions(new ResizeOptions(width, height))
                .build();

        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setOldController(simpleDraweeView.getController())
                .setImageRequest(request)
                .build();

        simpleDraweeView.setController(draweeController);
    }


    /**
     * 用浏览器打开地址
     */
    public static void openUrlByBrowser(String url) {
        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            try {
                if (url.startsWith("http:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                    PackageManager pm = MyApplication.getInstance().getPackageManager();
                    List<ResolveInfo> resolveList = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL);
                    if (null != resolveList && resolveList.size() > 0) {
                        LogUtil.i("resolveList size:" + resolveList.size());
                        String title = "choose application";
                        Intent intentChooser = Intent.createChooser(intent, title);
                        MyApplication.getInstance().getLastActivity().startActivity(intentChooser);
                    } else {
                        ToastUtil.showText("找不到可打开的应用");
                    }
                } else {
                    if (url.toLowerCase().endsWith(".apk")) {//是apk文件
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(new File(url)), "application/vnd.android.package-archive");
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        MyApplication.getInstance().startActivity(intent);
                        return;
                    }

                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri content_url = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        content_url = FileProvider.getUriForFile(MyApplication.getInstance(), "com.testdemo.fileProvider", new File(url));
                    } else {
                        content_url = Uri.fromFile(new File(url));
                    }
                    intent.setData(content_url);
                    //MyApplication.getInstance().getLastActivity().startActivity(intent);
                    PackageManager pm = MyApplication.getInstance().getPackageManager();
                    List<ResolveInfo> resolveList = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL);
                    if (null != resolveList && resolveList.size() > 0) {
                        LogUtil.i("resolveList size:" + resolveList.size());
                        String title = "choose application";
                        Intent intentChooser = Intent.createChooser(intent, title);
                        MyApplication.getInstance().getLastActivity().startActivity(intentChooser);
                    } else {
                        ToastUtil.showText("找不到可打开的应用");
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
